package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.StudentAccount;
import cn.wolfcode.crm.domain.Attendance;
import cn.wolfcode.crm.mapper.StudentAccountMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IStudentAccountService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class StudentAccountServiceImpl implements IStudentAccountService {

    @Autowired
    private StudentAccountMapper studentAccountMapper;
    
    public int saveOrUpdate(StudentAccount record) {
        if (record.getId() == null) {
            String password = record.getPassword();
            //安全操作 密码不为null的时候 才能加密
            if(password != null){
                //密码加密 (把用户名当做盐 并且加密2次)
                Md5Hash hash = new Md5Hash(password,record.getUsername(),2);
                //设置加密后的密码
                record.setPassword(hash.toString());
            }
            return studentAccountMapper.insert(record);
        } else {
            return studentAccountMapper.updateByPrimaryKey(record);
        }
    }
    
    public StudentAccount selectByPrimaryKey(Long id) {
        return studentAccountMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageResult query(QueryObject qo) {
        int count = studentAccountMapper.queryForcount(qo);
        if(count == 0){
            new PageResult(0, Collections.EMPTY_LIST);
        }
        List<Attendance> data = studentAccountMapper.queryList(qo);
        return new PageResult(count, data);
    }

    @Override
    public List<StudentAccount> selectAll() {
        return studentAccountMapper.selectAll();
    }
}
